import pycurl, json, StringIO, sys, time, Queue
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from tweetographerServer import StoreTweet

STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?locations=-74,40,-73,41" 

class Tweetographer:
	def __init__(self):
		self.buffer = ""
		self.userid = None
		self.conn = pycurl.Curl()
		self.tweetQueue = Queue.Queue()

	def connect(self, username, password):
		self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
		self.conn.setopt(pycurl.URL, STREAM_URL)
		self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
		print "Connected to Twitter API. Receiving Tweets."
		self.conn.perform()

	def on_receive(self, data):
		print "Recieved tweet."
		stored = ClientCreator(reactor, amp.AMP).connectTCP('127.0.0.1', 1234).addCallback(lambda p: p.callRemote(StoreTweet,data=str(data)))
		defer.DeferredList([stored])
		reactor.callLater(1, reactor.stop)
		reactor.run()
		#self.tweetQueue.put(data)
		

def main():
	tweetMe = Tweetographer()
	tweetMe.connect('Tweetographers','uc2302')

if __name__ == '__main__':
	main()
